import axios from "axios";
import router from "@/router";
import { Message } from "element-ui";
import store from '@/store'

import {
    baseURL,
    successCode,
    // tokenName,
    requestTimeout,
    contentType,
    // requestWhiteList
} from "@/config";

/**
 * @description 处理code异常
 * @param {*} code
 * @param {*} msg
 */
const handleCode = (code, msg) => {
    switch (code) {
        case 401:
            Message.error("登录身份已失效，请重新登录");
            break;
        case 403:
            Message.error("登录身份已失效，请重新登录");
            localStorage.clear()
            router.push({
                path: "/login",
            })
            break;
        default:
            Message.error(msg || `后端接口${code}异常`);
            break;
    }
};

/**
 * @description axios初始化
 */
const instance = axios.create({
    baseURL,
    timeout: requestTimeout,
    headers: {
        "Content-Type": contentType,
    },
});

/**
 * @description axios请求拦截器
 */
instance.interceptors.request.use(
    (config) => {
        // console.log(config);
        // var Authorization = localStorage.getItem('Authorization');
        // // 不在白名单中
        // if (!Array.from(requestWhiteList).includes(config.url)) {
        //     if (Authorization) {
        //         config.headers['Authorization'] = "Bearer " + Authorization
        //     } else {
        //         store.dispatch('user/userLoginOut').catch(() => {})
        //     }
        // }
        const token = store.state.user?.u_info?.token
        if (token) {
            config.headers['Authorization'] = "Bearer " + token
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

/**
 * @description axios响应拦截器
 */
instance.interceptors.response.use(
    (response) => {
        return response.data;
    },
    (error) => {
        const { response, message } = error;

        if (error.response && error.response.data) {
            const { status, data } = response;
            handleCode(status, data.detail || message);
            return Promise.reject(error);
        } else {
            let { message } = error;
            if (message === "Network Error") {
                message = "后端接口连接异常";
            }
            if (message.includes("timeout")) {
                message = "后端接口请求超时";
            }
            if (message.includes("Request failed with status code")) {
                const code = message.substr(message.length - 3);
                message = "后端接口" + code + "异常";
            }
            Message.error(message || `后端接口未知异常`);
            return Promise.reject(error);
        }
    }
);

export { instance };
